package com.example.controller;

import com.example.entity.ShopCart;
import com.example.entity.User;
import com.example.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/shopcart")
public class ShopCartController {

    @Autowired
    private ShopCartService shopCartService;

    // 获取购物车列表
    @GetMapping("/list")
    public String list(Model model, HttpSession session) {
        Integer userid = getUserIdFromSession(session); // 现在这个方法已定义

        List<ShopCart> shopcartList = shopCartService.getUserShopCarts(userid);
        System.out.println("购物车数据: " + shopcartList); // 确认数据
        model.addAttribute("shopcartList", shopcartList);

        // 计算总价
        Double totalPrice = 0.0; // 默认总价为0
        if (!shopcartList.isEmpty()) {
            String ids = shopcartList.stream()
                    .map(cart -> cart.getShopcartid().toString())
                    .collect(Collectors.joining(","));
            totalPrice = shopCartService.getTotalPrice(ids);
        }
        model.addAttribute("totalPrice", totalPrice);

        return "shopcart/list";
    }

    // 更新数量
    @PostMapping("/update")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateNum(
            @RequestParam Integer shopcartid,
            @RequestParam int num) {
        Map<String, Object> response = new HashMap<>();
        boolean success = shopCartService.updateCartNum(shopcartid, num);
        response.put("success", success);
        return ResponseEntity.ok(response);
    }

    // 删除商品
    @PostMapping("/delete/{shopcartid}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> deleteItem(
            @PathVariable("shopcartid") Integer shopcartid) {
        Map<String, Object> response = new HashMap<>();
        boolean success = shopCartService.deleteCartItem(shopcartid);
        response.put("success", success);
        return ResponseEntity.ok(response);
    }
    /**
     * 批量删除购物车商品
     */
    @PostMapping("/deleteBatch")
    @ResponseBody
    public String deleteBatch(String ids) {
        boolean success = shopCartService.deleteBatch(ids);
        return success ? "success" : "fail";
    }

    @PostMapping("/add")
    public String addToCart(
            @RequestParam Integer recipeid,
            HttpSession session) {

        // 1. 获取当前用户ID
        Integer userid = getUserIdFromSession(session);

        // 2. 构建购物车对象（简化版，数量默认为1）
        ShopCart shopCart = new ShopCart();
        shopCart.setUserid(userid);
        shopCart.setRecipeid(recipeid);
        shopCart.setNum(1); // 默认数量1

        // 3. 调用Service层
        shopCartService.addToCart(shopCart);

        // 4. 返回购物车列表页
        return "redirect:/shopcart/list";
    }



    /**
     * 从session中获取用户ID
     * @param session HttpSession对象
     * @return 用户ID
     * @throws RuntimeException 如果用户未登录或ID格式错误
     */
    private Integer getUserIdFromSession(HttpSession session) {
        Object userObj = session.getAttribute("user"); // 获取User对象
        if (userObj == null) {
            throw new RuntimeException("用户未登录，请先登录");
        }

        // 假设User类有getId()方法
        if (userObj instanceof User) {
            return ((User) userObj).getUserid(); // 从User对象中获取ID
        }

        throw new RuntimeException("会话中用户对象类型不正确");
    }
}